from django.shortcuts import render

from utils import restful
from .models import *
from .serializers import AllStudentSerializer


def login(request):
    username = request.POST.get('username')
    password = request.POST.get('password')
    try:
        person = Houseparent.objects.get(username=username, password=password)
        request.session['id'] = person.id
        request.session['name'] = person.name
        request.session['build_id'] = person.build_id_id
        return restful.ok(
            message="登陆成功！",
            data={'id': person.id, 'name': person.name, 'build_id': person.build_id_id}
        )
    except:
        return restful.params_error(message="账号或密码错误，请重新输入！")


def logout(request):
    request.session.flush()
    return restful.ok(data={'url': '/login.html'})


def login_html(request):
    return render(request, 'users/login.html')


def home(request):
    return render(request, 'home.html')


def MoveIn(request):
    room_id = request.GET.get('room_id')
    build_id = request.GET.get('build_id')
    student_number = request.GET.get('student_number')
    sex = request.GET.get('sex')
    student_obj = Student.objects.filter(student_number=student_number)
    # 先检查学号
    if student_obj:
        # 再检查性别
        student = student_obj.filter(sex=sex)
        if student:
            # 先获取当前学生的room_id,并将其先迁出,且入住人数-1
            cur_room_obj = student[0].room_id_id
            try:
                # 学生先迁出当前寝室
                cur_obj = Room.objects.filter(id=cur_room_obj)[0]
                cur_obj.actual_number -= 1
                cur_obj.save()
            except:
                pass
            # 更新传入的room_id
            student.update(room_id=room_id, build_id=build_id)
            obj = Room.objects.filter(id=room_id)[0]
            obj.actual_number += 1
            obj.save()
            return restful.ok(message='迁入成功')
        else:
            return restful.params_error(message='男女生不能混寝')
    else:
        return restful.params_error(message='学生学号不存在')


def MoveOut(request):
    room_id = request.GET.get('room_id')
    student_number = request.GET.get('student_number')
    student_obj = Student.objects.filter(student_number=student_number, room_id=room_id)
    if student_obj:
        student_obj.update(room_id=None, build_id=None)
    else:
        return restful.params_error(message="该学生不在该寝室！")
    obj = Room.objects.filter(id=room_id)[0]
    obj.actual_number -= 1
    obj.save()

    return restful.ok(message="迁出成功")


def get_student_info(request):
    sex = request.GET.get('sex')
    obj = Student.objects.filter(sex=sex)
    data = AllStudentSerializer(obj, many=True).data

    return restful.ok(data=data)
